package com.itheima.test07;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
服务端 接受上传的文件 并保存到服务器的磁盘 并给出响应
 */
public class ServerDemo {

    public static void main(String[] args) throws IOException {
        ExecutorService pool = Executors.newCachedThreadPool();

        //创建服务器对象
        ServerSocket ss = new ServerSocket(8888);
        while (true) {
            //建立连接
            Socket accept = ss.accept();
            UploadThread upload = new UploadThread(accept);
            pool.submit(upload);
        }
        //ss.close();

    }
}

class UploadThread implements Runnable {

    private Socket accept;

    public UploadThread(Socket accept) {
        this.accept = accept;
    }

    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name+"正在工作");
        BufferedOutputStream bos = null;
        BufferedWriter writer = null;
        try {
            //获取输入流
            InputStream is = accept.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            //创建 磁盘输出流
            //起名字   起不能重复的名字
            bos = new BufferedOutputStream(new FileOutputStream("day16\\copy\\" + UUID.randomUUID() + ".jpg"));
            byte[] bytes = new byte[1024];
            int len;
            //边读边写
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            bos.flush();
            //向服务器响应 上传成功
            //获取 输出流
            OutputStream os = accept.getOutputStream();
            writer = new BufferedWriter(new OutputStreamWriter(os));

            //写数据
            writer.write("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //各种释放资源
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
